// import User from '../model/user'
// import ApiError from '../error/ApiError'
// import ApiErrorNames from '../error/ApiErrorNames'
import jwt from 'jsonwebtoken'
import { jwtConfig } from '../config/index'
import Shop from '../model/shop'
import Orders from '../model/orders'
import { getshopid, getshopinfo } from '../utils/getWebAjax'
import moment from 'moment'
// import { rightsInfo } from '../api/token'

// import * as jwt from "jsonwebtoken";
// import {jwtConfig} from "../config/index";
class UserController {
	// 触发注册 保存用户信息等逻辑
	static async getUserToken(ctx) {
		const { shop_id = '', shop_phone = '' } = ctx.query
		const shopid = await getshopid(ctx)
		if (!shopid.code) {
			if (shopid.data.shop_id * 1 !== shop_id * 1) {
				ctx.body = {
					code: 4370,
					msg: 'shop_id不匹配',
				}
				return
			}
			const shopData = await Shop.findOne({
				shop_id: shopid.data.shop_id,
			})

			if (shopData) {
				// console.log('shopData', shopData)
				if (!shopData.openForBusinessTime) {
					if (ctx.header.t) {
						const shopinfo = await getshopinfo(ctx)
						// console.log('shopinfo00', shopinfo)
						shopData.openForBusinessTime = shopinfo.data.qual_status_info.audit_time
						shopData.save()
					}

				}
				if (shopData.isBuy == 3) {
					// 过期 则清空店铺积分
					shopData.aiRemainScore = 0
					await shopData.save()
				}
				const token = jwt.sign(
					{
						access_token: shopData.access_token || '',
						shop_name: shopData.shop_name || '',
						shop_id: shopData.shop_id,
						for: 'dy-shop'
					},
					jwtConfig.secret,
					{ expiresIn: '30d' }
				)
				ctx.body = { token }
				// if(shopData.access_token)
				// console.log('shopData012', shopData,  ((new Date().getTime() - new Date(shopData.updateTime).getTime())/1000) , shopData.expires_in)
				// if (shopData.access_token && (((new Date().getTime() - new Date(shopData.updateTime).getTime())/1000) < shopData.expires_in)) {
				// 	// console.log('access_token 为过期',)
				// 	// const rightsInfoData = await rightsInfo({
				// 	// 	access_token: shopData.access_token,
				// 	// })
				// 	// if (rightsInfoData.code == 10000) {
				// 	// 	if (moment(rightsInfoData.data.expire_time).isAfter(moment())) {
				// 	// 		shopData.isBuy = rightsInfoData.data.rights_type ? 1 : 2
				// 	// 		shopData.service_end_time = new Date(rightsInfoData.data.expire_time).getTime() / 1000
				// 	// 		await shopData.save()
				// 	// 	}
				// 	// }
				// }
				return
			}
			// 检查订单列表是否存在该店铺的近期订购未到期的订单 没有手动删除不需要这个动作
			const shopinfo = await getshopinfo(ctx)
			// console.log('shopinfo00', shopinfo)
			const shopInfoSaveData = { shop_name: '', openForBusinessTime: '' }
			if (!shopinfo.code) {
				shopInfoSaveData.shop_name = shopinfo.data.shop_name
				shopInfoSaveData.openForBusinessTime =
					shopinfo.data.qual_status_info.audit_time
			}
			let outTime = ''
			let isBuy = 0
			let service_end_time = ''
			// 检查order表格是否存在订购信息
			const userOrdersData = await Orders.find({ shop_id: shopid.data.shop_id })
				.sort({ createTime: -1 })
				.limit(1)
				.exec()
			if (userOrdersData.length) {
				const userOrdersDataItem = userOrdersData[0]
				outTime = moment(userOrdersDataItem.service_end_time * 1000).isBefore(moment())
				service_end_time = userOrdersDataItem.service_end_time
				if (userOrdersDataItem.pay_type === 7 && !outTime) {
					isBuy = 2 // 试用版没过期

				}
				if (userOrdersDataItem.pay_type !== 7 && !outTime) {
					isBuy = 1 // 付费没过期

				}
				if (outTime) {
					isBuy = 3 // 已经过期

				}
			}

			// service_end_time是否过期
			const shop_data = new Shop({
				shop_id: shopid.data.shop_id,
				shop_phone,
				...shopInfoSaveData,
				isBuy,
				expireTime: service_end_time
			})
			await shop_data.save()
			const token = jwt.sign(
				{
					shop_phone,
					access_token: '',
					shop_name: '',
					shop_id: shopid.data.shop_id,
				},
				jwtConfig.secret,
				{ expiresIn: '30d' }
			)
			ctx.body = { token }
			return
		}
		ctx.body = {
			code: 4371,
			msg: 'shop_id不存在',
			data: shopid,
		}
	}
	static async checkBuy(ctx) {
		const jwtstr = ctx.header.authorization.split('Bearer ')[1]
		const jwtdata = await jwt.verify(jwtstr, jwtConfig.secret)
		ctx.body = jwtdata
	}
	static async checkUserPhone(ctx) {
		// 检查是否已经获取到用户的两个手机号
		// console.log('process.env.AOT_ALL_SHOP', process.env.AOT_ALL_SHOP)
		const { shop_id } = ctx.query
		if (global.WhiteList.includes(shop_id + '') || process.env.AOT_ALL_SHOP === 'Y') {
			ctx.body = {
				shop_phone: true,
				user_phone: true,
			}
			return
		}
		const shopusers = await Shop.findOne({ shop_id })

		if (!shopusers) {
			ctx.body = {
				code: 4388,
				msg: '店铺不存在',
			}
			return
		}
		ctx.body = {
			shop_phone: !!shopusers.shop_phone,
			user_phone: !!shopusers.user_phone,
		}
	}
	static async saveUserPhone(ctx) {
		const { shop_id, user_phone, shop_phone } = ctx.query

		if (global.WhiteList.includes(shop_id + '') || process.env.AOT_ALL_SHOP === 'Y') {
			ctx.body = {
				msg: 'ok',
			}
			return
		}
		const shopusers = await Shop.findOne({ shop_id })

		if (!shopusers) {
			ctx.body = {
				code: 4388,
				msg: '店铺不存在',
			}
			return
		}
		const asvedataformat = {}
		if (user_phone) {
			asvedataformat.user_phone = user_phone
		}
		if (shop_phone) {
			asvedataformat.shop_phone = shop_phone
		}
		if (!Object.keys(asvedataformat).length) {
			ctx.body = {
				code: 4343,
				msg: '没有需要保存的数据',
			}
			return
		}
		await Shop.findOneAndUpdate(
			{ shop_id: shop_id },
			{
				$set: asvedataformat,
			},
			{ upsert: true }
		)
		ctx.body = {
			msg: 'ok',
		}
	}
}

export default UserController
